# -*- coding:UTF-8 -*-
"""
这个文件是密码分发端的主程序，包含密码随机生成，密码分发功能
"""
import tornado.web
import tornado.ioloop
import tornado.gen
import urllib
import urllib2
import seccure
import random
import multiprocessing
import dbopt
import os

servie_pub_key = ">xzeLw2u85S%Lub0e)zTf]2V8"
test_pr_key = "i am test key"
ran = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"

settings = {
    "static_path":os.path.join(os.path.dirname(__file__), "static"),
    "cookie_secret": "61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
    "login_url": "/",

}

class postor():#跟服务端一样　不赘述了
    def __init__(self,address,data):
        self.value = urllib.urlencode(data)
        self.req = urllib2.Request(address,self.value)

    def post_data(self):
        res = urllib2.urlopen(self.req)
        print res.read()
        return res

def post_t(address,value):
    pos = postor(address, value)
    print "do posting"
    pos.post_data()

class Mainhandler(tornado.web.RequestHandler):
    def make_password(self):#创建随机码的函数
        sl = random.sample(ran,8)
        #print sl
        str = ""
        for x in sl:
            str = str+x
        return str
    def get_user_pub(self,name):# 获取用户公钥
        db = dbopt.db_class()
        cu = db.get_uesr_pub(name)
        dict = cu.next()
        return  dict["pub"]
    def post(self):
        ip = self.get_argument("ip")
        address = 'http://'+ip+':8888/'
        name = self.get_argument("name")
        s = self.get_argument("s")
        sig = self.get_argument("sig")#获得从客户端传输来的数据
        print(ip + "  " + s + "  " + name + "   " + sig)
        if(seccure.verify(str(s),sig,servie_pub_key)):#验证客户端签名
            password_d = self.make_password()
            s = "hello"
            sig = seccure.sign(s,"i am test key")
            password_for_user = seccure.encrypt(password_d,self.get_user_pub(name).decode("base64"))#用用户的公钥加密给用户的随机码
            password_for_servie = seccure.encrypt(password_d,servie_pub_key)#用服务端的公钥加密给服务端的随机码
            value = {}
            value['name'] = name
            value['data'] = password_for_user.encode("base64")
            value['s'] = s
            value['sig'] = sig
            print(value)
            self.write(password_for_servie.encode("base64"))
            p = multiprocessing.Process(target=post_t,args=(address,value,))#创建新进程进行通信，分发随机码
            p.start()
        else:
            self.write("error")
    def get(self):
        self.write("welcome to ca center")

class RegistHandler(tornado.web.RequestHandler):#注册页面用的后台
    def get(self):
        self.render("static/html/regist.html")
    @tornado.gen.engine
    @tornado.web.asynchronous
    def post(self):
        username = self.get_argument("username")#获得账号
        password = self.get_argument("password")#获得密码
        key = seccure.generate_keypair()#生成密钥对
        db = dbopt.db_class()
        print username
        if(db.check_user(username)==0):
            db.add_user(username,key[1])
            data = {"username":username,"password":password,"power":"M"}
            p = multiprocessing.Process(target=post_t,args=("http://localhost:8081/add",data,))
            p.start()#通知服务端有用户注册
            self.set_header('Content-Type', 'application/octet-stream')
            self.set_header('Content-Disposition', 'attachment; filename=' + username+".key")
            file_str = username+";"+key[0].encode("base64")+";"+key[1].encode("base64")
            file_str_e = seccure.encrypt(file_str.encode("base64"),"CRwhC^:1<1g.<fYk#FcG:^E}M")#生成加密证书
            print file_str
            self.write(file_str_e)#给予证书下载
            self.finish()

application = tornado.web.Application([(r'/',Mainhandler),
                                       (r'/regist',RegistHandler),
                                       ],**settings)

if __name__ == '__main__':
    application.listen(8088)
    tornado.ioloop.IOLoop.instance().start()
